package com.lyc.controller.admin;

import com.lyc.pojo.Category;
import com.lyc.pojo.Result;
import com.lyc.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/admin/category")
@Slf4j
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;


    /**
     * 获取所有版块
     * @return 版块列表
     */
    @GetMapping
    public Result<List<Category>> getAllCategories() {
        log.info("获取所有版块");

        List<Category> categories = categoryService.getAllCategories();
        log.info("成功获取{}个版块", categories.size());
        return Result.success(categories);
    }

    /**
     * 添加版块
     * @param category 版块信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public Result addCategory(@RequestBody Category category) {
        log.info("添加新版块: {}", category.getName());

        // 设置创建时间和更新时间
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        
        categoryService.addCategory(category);
        log.info("成功添加版块，ID: {}", category.getId());
        return Result.success();
    }
    
    /**
     * 更新版块
     * @param category 版块信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result updateCategory(@RequestBody Category category) {
        log.info("更新版块: ID={}, 名称={}", category.getId(), category.getName());

        // 设置更新时间
        category.setUpdatedAt(LocalDateTime.now());
        
        categoryService.updateCategory(category);
        log.info("成功更新版块: ID={}", category.getId());
        return Result.success();
    }
    
    /**
     * 删除版块
     * @param id 版块ID
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public Result deleteCategory(@RequestParam Integer id) {
        log.info("删除版块: ID={}", id);

        categoryService.deleteCategory(id);
        log.info("成功删除版块: ID={}", id);
        return Result.success();
    }
    
    /**
     * 更新版块状态
     * @param id 版块ID
     * @param status 版块状态
     * @return 操作结果
     */
    @PatchMapping("/status")
    public Result updateCategoryStatus(@RequestParam Integer id, @RequestParam String status) {
        log.info("更新版块状态: ID={}, 状态={}", id, status);

        Category category = categoryService.getCategoryById(id);
        if (category != null) {
            category.setStatus(status);
            category.setUpdatedAt(LocalDateTime.now());
            categoryService.updateCategory(category);
            log.info("成功更新版块状态: ID={}, 新状态={}", id, status);
            return Result.success();
        } else {
            log.warn("更新版块状态失败: 版块不存在, ID={}", id);
            return Result.error("版块不存在");
        }
    }
}